package com.joven.security.filter;

import com.joven.security.model.LoginUser;
import com.joven.security.utils.JwtUtils;
import com.joven.security.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author wzj
 * @Date 2023-03-01 10:07
 **/
@Component
public class TokenFilterComponent extends OncePerRequestFilter {
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            //未获取到token信息，直接放行，SecurityContextHolder无用户信息，会被拦截器拦截
            filterChain.doFilter(request, response);
            return;
        }
        Boolean tokenExpired = jwtUtils.isTokenExpired(token);
        if (tokenExpired) {
            throw new RuntimeException("token已过期，请重新登陆！");
        }
        //解析jwt token,获取用户id
        Claims claimsFromToken = jwtUtils.getClaimsFromToken(token);
        Integer id = (Integer) claimsFromToken.get("USERID");
        //根据用户id查询缓存中用户信息
        LoginUser loginUser = (LoginUser) redisUtils.get("loginUser:" + id);
        if (loginUser == null) {
            throw new RuntimeException("非法用户！");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        //认证通过，将用户信息存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
